import { Navigate, Route, Routes } from "react-router-dom"
import KeepAlive from "react-activation"
import Login from "@/page/LoginRegister/login"
import Register from "@/page/LoginRegister/register"
import Home from "@/page/Home/index"
import Detail from "@/page/Detail/index"
import Category from "@/page/Category/index"
import Shopcart from "@/page/Shopcart/index"
import Mine from "@/page/Mine/index"
import Collect from "@/page/Mine/components/Collect/index"
import Address from "@/page/Mine/components/Address/index"
import EditAddress from "@/page/Mine/components/EditAddress/index"

const Router = () => {
  const routes = [
    {path: '/login', element: <Login/>},
    {path: '/register', element: <Register/>},
    {path: '/home', element: <Home/>, keepAlive: true},
    {path: '/category', element: <Category/>, keepAlive: true},
    {path: '/detail', element: <Detail/>, keepAlive: true},
    {path: '/shopcart', element: <Shopcart/>, keepAlive: true},
    {path: '/mine', element: <Mine/>, keepAlive: true},
    {path: '/collect', element: <Collect/>},
    {path: '/address', element: <Address/>},
    {path: '/editAddress', element: <EditAddress/>},
    {path: '/', element: <Navigate to='/home'/>},
    {path: '*', element: <Navigate to='/home'/>}
  ]

  const hasKeepAlive = (item: {path: string, element: any}) => {
    return (
      <KeepAlive when={[true, true]} saveScrollPosition={'screen'} key={item.path}>{item.element}</KeepAlive> 
    )
  }

  const show = (item: any) => {
    if(item.keepAlive) { // 需要缓存
      return (
        <Route path={item.path} key={item.path} element={hasKeepAlive(item)}>
          {item.children && RouteNav(item.children)}
        </Route>
      )  
    } else { // 不需要缓存
      return (
        <Route path={item.path} key={item.path} element={item.element}>
          {item.children && RouteNav(item.children)}
        </Route>
      )  
    }
  }

  const RouteNav = (params: any) => {
    return params.map((item: any) => {
      return show(item)
    })
  }

  return (
    <Routes>
      {RouteNav(routes)}
    </Routes>
  )
}

export default Router